<?php
/**
 * @package AMFramework
 * @subpackage Data_Pack
 * @author Marcu Alexandru
 * @version 1.0 $Build 305b  
 */
class Amfw_Template_Parser implements Amfw_Template_IParser
{
	public static function getInstance()
	{
		static $instance;
		if(is_null($instance)):
			$instance = self::_create();
			endif;
		return $instance;
	}
	public function parseTemplate($template, $pattern, $behav = self::PARSE_ALL)
	{
		$html = $this->_getHtmlFromTemplate($template, $pattern);
		$parsed_html = $this->_parser($html, $template, $behav);
		return $parsed_html;
	}
	private function _getHtmlFromTemplate($template, $pattern)
	{	// In order for this method to work, it should be called using the template
		// TODO: Doesn't really give any flexibility to a template (for patterns)
		// This method really needs to be raised from peasentry
		if(is_subclass_of($template,'Amfw_Template')) {
			$html = @Amfw_Utils::obImport( TMPL_PATH.DS.get_class($template).DS.$pattern.'.phtml' );
			return $html;
		}
		return null;
	}
	private function _parser($html, $template, $behav = self::PARSE_ALL)
	{
		if($behav > self::PARSE_USER):
			global $framework;
			$doc = @$framework->getDocument();
			if(!isset($doc)) return;
			endif;
		switch($behav)
		{
			case self::PARSE_ALL:
				if($behav != self::PARSE_ALL) break;
			case self::PARSE_USER:
				// Getting the name of the interface our template implements
				$tmp = class_implements($template,true);
				//Careful here, the interface which contains the methods which we need should be the last one declared
				if(is_array($tmp)) $tmp = array_pop($tmp);
				// If we have a class to use
				if(isset($tmp))
				{
					// Getting the actual methods from the interface
					$methods = get_class_methods($tmp);
						
					foreach($methods as $userdef) {
						$needle = '{'.$userdef.'}';
						$replace = $template->$userdef(); //Runs the user-defined method for to replace the surrogate with
						$html = str_replace($needle,$replace,$html); // This low-class way should probably be knighted
					}
				}
				if($behav == self::PARSE_USER) break;
			case self::PARSE_DOC:
				$tmp = class_implements('Amfw_Document',true);
				if(is_array($tmp)) $tmp = array_pop($tmp);
				// If we have a class
				if(isset($tmp))
				{
					// Getting the actual methods
					$methods = get_class_methods($tmp);
	
					foreach($methods as $regdef) {
						$needle = '{'.$regdef.'}';
						$replace = $doc->$regdef(); // That's why we needed to get the document at the beginning!
						$html = str_replace($needle, $replace, $html);
					}
				}
				break;
		}
		return $html;
	}
	private static function _create()
	{	// Creation method for Singleton.
		return new Amfw_Template_Parser;
	}
}